﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Text;
using log4net;
using Textile;

namespace Edge.Common.Utils
{
    /// <summary>
    /// Summary description for StringUtils.
    /// </summary>
    public sealed class StringUtils
    {

        private readonly static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static string Trunk(string s, int length, string suffix)
        {
            if (s == null) return string.Empty;

            if (s.Length > length)
                return s.Substring(0, length) + suffix;
            else
                return s;
        }

        public static string TrunkBySpace(string s, int length, string suffix)
        {
            if (s == null) return string.Empty;

            if (s.Length > length && s.IndexOf(" ") != -1)
            {
                int i = 0;
                while (s.Substring(0, length - i)[length - i - 1].ToString() != " ")
                    i++;
                return s.Substring(0, length - i - 1) + suffix;
            }
            else
                return s;
        }

        public static string TrunkBySymbol(string s, int length, string symbol)
        {
            if (s == null) return string.Empty;

            if (s.Length > length && s.IndexOf(symbol) != -1)
                return s.Substring(0, s.IndexOf(symbol));
            else
                return s;
        }

        public static bool IsEmptyOrNull(string s)
        {
            return s == string.Empty || s == null;
        }

        public static bool IsBlankOrNull(string s)
        {
            return s == null || s.Trim().Length == 0;
        }


        public static string EmptyToNull(string s)
        {
            return s == string.Empty ? null : s;
        }

        public static string NullToEmpty(string s)
        {
            return s ?? string.Empty;
        }


        /// <summary>
        /// TODO escape synbol ','
        /// </summary>
        /// <param name="objs"></param>
        /// <returns></returns>
        public static string ToStringCommaSeparated(IEnumerable objs)
        {
            StringBuilder buffer = new StringBuilder();
            int idx = 0;
            foreach (object obj in objs)
            {
                if (idx > 0)
                    buffer.Append(',');

                buffer.Append(obj);

                idx++;
            }
            return buffer.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public static object[] ToObjectArray(string s, params Type[] types)
        {
            string[] ss = s.Split(',');
            if (ss.Length != types.Length)
                throw new ArgumentException("s");
            object[] ret = new object[ss.Length];
            for (int i = 0; i < ss.Length; i++)
                ret[i] = Convert.ChangeType(ss[i], types[i]);
            return ret;
        }

        public static string EncodeForFormat(string value)
        {
            value = value.Replace("{", "{{");
            value = value.Replace("}", "}}");
            return value;
        }

        public static DateTime LoadDateTimeForDB(string value)
        {

            DateTime ret = SqlDateTime.MinValue.Value;

            try
            {
                if (value.Trim().Length > 0) ret = Convert.ToDateTime(value);
            }
            catch (Exception ex)
            {
                log.Error("", ex);
                ret = SqlDateTime.MinValue.Value;
            }

            return ret;
        }

        public static bool Contains(string text, params string[] strings)
        {
            foreach (string s in strings)
            {
                if (s != null && s.ToLower().Contains(text.ToLower()))
                    return true;
            }
            return false;
        }

        public static string Exception(Exception ex)
        {
            if (ex == null)
                throw new ArgumentException("ex");
            StringBuilder ret = new StringBuilder();

            while (ex != null)
            {
                ret.Append(ex.ToString());
                ret.Append(Environment.NewLine);
                ex = ex.InnerException;
            }
            return ret.ToString();
        }

        public static byte[] ConvertArray(char[] chars)
        {
            if (chars == null)
                return null;

            List<byte> ret = new List<byte>(chars.Length);
            for (int i = 0; i < chars.Length; i++)
            {
                //                ret.AddRange(BitConverter.GetBytes(chars[i]));
                ret.Add(Convert.ToByte(chars[i]));
            }
            return ret.ToArray();
        }

        public static char[] ConvertArray(byte[] bytes)
        {
            if (bytes == null)
                return null;
            char[] ret = new char[bytes.Length];
            for (int i = 0; i < bytes.Length; i++)
            {
                ret[i] = Convert.ToChar(bytes[i]);
            }

            return ret;
        }

        public static string TextileToHtml(object input)
        {
            string ret = string.Empty;
            StringBuilderTextileFormatter sbtf = new StringBuilderTextileFormatter();
            TextileFormatter textileFormatter = new TextileFormatter(sbtf);
            textileFormatter.Format(input.ToString());
            ret = sbtf.GetFormattedText();
            return ret;
        }

        public static List<string> Parse(string str, string symbol)
        {
            List<string> ret = new List<string>();
            if (str.Contains(symbol))
            {
                int i = str.IndexOf(symbol);
            }
            return ret;
        }

    }
}
